<template>
  <div class="publish-page">
    <!-- 顶部操作栏：关闭 + 发布按钮 -->
    <div class="top-bar">
      <button class="close-btn" @click="handleClose">×</button>
      <button class="publish-btn" @click="handlePublish">发布</button>
    </div>

    <!-- 标题输入区域 -->
    <input
      v-model="title"
      placeholder="请输入标题"
      class="title-input"
    />

    <!-- 图片区域：预览 + 添加按钮 -->
    <div class="img-container">
      <div class="img-item" v-for="(img, idx) in imageList" :key="idx">
        <img :src="img" alt="图片预览" class="preview-img" />
        <button class="delete-img" @click="handleDeleteImage(idx)">×</button>
      </div>
      <div class="add-img-btn" @click="handleAddImage">+</div>
    </div>

    <!-- 输入区域：分享心得 -->
    <textarea
      v-model="content"
      placeholder="分享下你的下厨心得、生活点滴"
      class="content-input"
    ></textarea>

    <!-- 标签区域 -->
    <div class="tag-section">
      <div class="tag-header">
        <span class="tag-icon">#</span>
        <span class="tag-title">标签</span>
        <button class="more-tag-btn" @click="toggleTagView">
          {{ isTagExpanded ? '<' : '>' }}
        </button>
      </div>
      <div class="tag-list-container" :class="{ expanded: isTagExpanded }">
        <div class="tag-list">
          <button
            v-for="tag in tags"
            :key="tag"
            class="tag-btn"
            :class="{ active: selectedTags.includes(tag) }"
            @click="toggleTag(tag)"
          >
            {{ tag }}
          </button>
        </div>
      </div>
    </div>

    <!-- 同步到微信 -->
    <div class="sync-section">
      <img
        src=""
        alt="微信图标"
        class="weibo-icon"
      />
      <span class="sync-text">同步到微信</span>
      <van-switch v-model="isSyncToWeibo" size="20" />
    </div>
     <input
    type="file"
    ref="fileInput"
    accept="image/*"
    multiple
    class="hidden"
    @change="handleFileSelect"
  />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Switch, showSuccessToast, showFailToast } from 'vant';
import { useRouter } from 'vue-router';
import api from '@/api';

// 响应式数据
const imageList = ref([]);
const fileInput = ref(null); // 绑定文件选择框
const content = ref(''); // 输入的文字内容
const title = ref(''); // 标题内容
const tags = ref([]); // 标签列表（从后端获取）
const selectedTags = ref([]); // 选中的标签
const isSyncToWeibo = ref(false); // 是否同步到微信
const isTagExpanded = ref(false); // 控制标签是否展开
const admin = JSON.parse(localStorage.getItem("admin") || 'null')
const router=useRouter();
const fileList = ref([]); 

// 组件挂载时获取标签列表
onMounted(() => {
  fetchTags();
});

// 从后端获取标签列表
const fetchTags = async () => {
  try {
    const response = await api.getReq('/category/selectAllTypeName'); // 假设后端接口为/tags/list
    if (response.data.code === 1) {
      tags.value = response.data.data || ['宵夜', '晚餐', '下午茶', '午餐', '早餐', '家常菜', '快手菜', '甜点', '素食', '肉类', '海鲜', '汤品'];
    } else {
      showFailToast('获取标签失败');
      // 失败时使用默认标签
      tags.value = ['宵夜', '晚餐', '下午茶', '午餐', '早餐', '家常菜', '快手菜', '甜点', '素食', '肉类', '海鲜', '汤品'];
    }
  } catch (error) {
    console.error('获取标签错误:', error);
    showFailToast('网络错误，无法获取标签');
    tags.value = ['宵夜', '晚餐', '下午茶', '午餐', '早餐', '家常菜', '快手菜', '甜点', '素食', '肉类', '海鲜', '汤品'];
  }
};

// 关闭页面
const handleClose = () => {
  console.log('关闭发布页面');
  router.push('/post');
};

// 发布帖子
const handlePublish=()=>{
  // 简单验证
  if (!title.value.trim()) {
    showFailToast('请输入标题');
    return;
  }
  
  if (!content.value.trim() && imageList.value.length === 0) {
    showFailToast('请添加内容或图片');
    return;
  }
  
  const formData = new FormData();
  formData.append("userId", admin.id);
  formData.append("title", title.value);
  formData.append("content", content.value);
  
  // 添加选中的标签
  if (selectedTags.value.length > 0) {
    formData.append("tags", selectedTags.value.join(','));
  }
  
  // 添加图片
  fileList.value.forEach((file) => {
    formData.append('myHeads', file, file.name);
  });
  
  // 添加同步信息
  formData.append("syncToWechat", isSyncToWeibo.value);
  
  api.postReq('/post/addPost', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    let result = res.data;
    if (result.code === 1) {
      showSuccessToast(result.msg);
      router.back();
    } else {
      showFailToast(result.msg);
    }
  }).catch(error => {
    console.error('发布失败:', error);
    showFailToast('发布失败，请重试');
  });
}

// 添加图片
const handleAddImage = () => {
  fileInput.value.click();
};

// 删除图片
const handleDeleteImage = (index) => {
  imageList.value.splice(index, 1);
  fileList.value.splice(index, 1);
};

// 处理选中的图片文件
const handleFileSelect = (e) => {
  const files = e.target.files;
  if (!files.length) return;

  // 遍历选中的文件
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    // 验证是否为图片类型
    if (!file.type.startsWith('image/')) {
      showFailToast('请选择图片文件！');
      continue;
    }
    
    // 限制最多上传9张图片
    if (imageList.value.length >= 9) {
      showFailToast('最多只能上传9张图片');
      break;
    }
    
    // 保存原始文件对象（用于上传）
    fileList.value.push(file);

    // 读取文件并转换为可预览的URL
    const reader = new FileReader();
    reader.onload = (event) => {
      // 将图片URL添加到列表
      imageList.value.push(event.target.result);
    };
    reader.readAsDataURL(file);
  }

  // 清空input值，避免重复选择同一文件时不触发change事件
  e.target.value = '';
};

// 切换标签选中状态，并在content中添加/移除标签
const toggleTag = (tag) => {
  const index = selectedTags.value.indexOf(tag);
  if (index > -1) {
    // 取消选中，从content中移除标签
    selectedTags.value.splice(index, 1);
    // 使用正则表达式移除标签，避免影响其他内容
    const reg = new RegExp(`#${tag}#`, 'g');
    content.value = content.value.replace(reg, '').trim();
  } else {
    // 选中，向content中添加标签
    selectedTags.value.push(tag);
    // 在内容末尾添加标签，保持格式整洁
    content.value = `${content.value} #${tag}#`.trim();
  }
};

// 切换标签展开/收起状态
const toggleTagView = () => {
  isTagExpanded.value = !isTagExpanded.value;
};
</script>

<style scoped>
.hidden {
  display: none;
}
.publish-page {
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;
  max-width: 600px;
  margin: 0 auto;
}

/* 顶部栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.close-btn {
  font-size: 24px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: #333;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background-color: #f5f5f5;
}

.publish-btn {
  background-color: #ff6b6b;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.publish-btn:hover {
  background-color: #ff5252;
}

/* 标题输入区域 */
.title-input {
  width: 100%;
  height: 40px;
  border: none;
  outline: none;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.title-input::placeholder {
  color: #ccc;
}

/* 图片区域 */
.img-container {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.img-item {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  background-color: #f9f9f9;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-img {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.img-item:hover .delete-img {
  opacity: 1;
}

.add-img-btn {
  width: 120px;
  height: 120px;
  border: 1px dashed #ddd;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32px;
  color: #ddd;
  cursor: pointer;
  background-color: #f9f9f9;
  transition: all 0.2s;
}

.add-img-btn:hover {
  border-color: #ff6b6b;
  color: #ff6b6b;
  background-color: #fff5f5;
}

/* 输入区域 */
.content-input {
  width: 100%;
  min-height: 120px;
  border: none;
  outline: none;
  resize: none;
  font-size: 16px;
  color: #333;
  margin-bottom: 24px;
  padding: 8px 0;
  line-height: 1.5;
}

.content-input::placeholder {
  color: #ccc;
}

/* 标签区域 */
.tag-section {
  margin-bottom: 24px;
}

.tag-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.tag-icon {
  font-size: 20px;
  color: #ff6b6b;
  margin-right: 4px;
}

.tag-title {
  font-size: 16px;
  color: #333;
  margin-right: auto;
}

.more-tag-btn {
  border: none;
  background: transparent;
  color: #999;
  cursor: pointer;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.more-tag-btn:hover {
  background-color: #f5f5f5;
  color: #ff6b6b;
}

.tag-list-container {
  overflow: hidden;
  max-height: 40px; /* 只显示一行标签的高度 */
  transition: max-height 0.3s ease;
}

.tag-list-container.expanded {
  max-height: 200px; /* 展开时的最大高度，可以根据需要调整 */
  overflow-y: auto; /* 当标签过多时显示滚动条 */
  padding-right: 8px; /* 为滚动条预留空间 */
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding-bottom: 8px;
}

.tag-btn {
  padding: 6px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background: transparent;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  white-space: nowrap; /* 确保标签文字不换行 */
}

.tag-btn:hover {
  border-color: #ff6b6b;
  color: #ff6b6b;
}

.tag-btn.active {
  background-color: #ff6b6b;
  color: #fff;
  border-color: #ff6b6b;
}

/* 同步区域 */
.sync-section {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-top: 1px solid #f5f5f5;
}

.weibo-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.sync-text {
  font-size: 16px;
  color: #333;
  margin-right: auto;
}

/* 滚动条样式优化 */
.tag-list-container::-webkit-scrollbar {
  width: 6px;
}

.tag-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.tag-list-container::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}

.tag-list-container::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}
</style>
